<?php
/**
 * Post Controller
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD
 * @license http://doit.yuandot.com/license/
 */

class PostsController extends Controller {
    function init() {
        $this->layout = 'contents';
    }

    const PAGE_SIZE = 14;

    /**
     * @var string specifies the default action to be 'index'.
     */
    public $defaultAction = 'index';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'index' and 'show' actions
                'actions' => array('index', 'changeStatus', 'changeRecommend', 'changePicking'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'batchProcess' actions
                'actions' => array('admin', 'batchProcess'),
                'users' => array('admin'),
            ),
            array('deny',  // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all post
     */
    public function actionIndex() {
        $current_node = Yii::app()->request->getParam('node');
        $criteria = new CDbCriteria;
        $criteria->condition = 'status != ' . Options::STATUS_PENDING_DELETE;
        if (intval($current_node)) {
            $criteria->addCondition("node_id = {$current_node}");
        }

        $pages = new CPagination(Post::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort = new CSort('Post');
        $sort->applyOrder($criteria);

        $models = Post::model()->findAll($criteria);

        $this->render('index',array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
            'current_node' => $current_node,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'index' page.
     */
    public function actionCreate() {
        $model = new Post;
        $model->node_id = Yii::app()->request->getParam('node');
        $model->order_pos = 0;
        $model->published_at = date('Y-m-d', time());
        $model->author = Yii::app()->params['frontend']['site_name'];
//        CVarDumper::dump($model);
        if (isset($_POST['Post'])) {
            $model->attributes = $_POST['Post'];
            if ($model->save()) {
                $this->redirect(array('index', 'node' => $_POST['Post']['node_id']));
            }
        }
        $this->render('create', array('model' => $model));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'index' page.
     */
    public function actionUpdate() {
        $model = $this->loadPost();
        if (isset($_POST['Post'])) {
            $model->attributes = $_POST['Post'];
            if ($model->save()) {
                $this->redirect(array('index', 'node' => $_POST['Post']['node_id']));
            }
        }
        $this->render('update', array('model' => $model));
    }

    // change status
    public function actionChangeStatus() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Post::model()->findByPk($id);
            switch ($model->status) {
                case Options::STATUS_DRAFT:
                    $status = Options::STATUS_PUBLISHED;
                    break;
                case Options::STATUS_PUBLISHED:
                    $status = Options::STATUS_DRAFT;
                    break;
            }
            $model->status = $status;
            try {
                $model->save(false);
//                print_r($model->getErrors());
            } catch (Exception $ex) {
                echo $ex;
            }
            
            echo $model->statusIconFormat;
        }
    }

    /**
     * change "is_recommend" value, false or true
     */
    public function actionChangeRecommend() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Post::model()->findByPk($id);
            $value = (intval($model->is_recommend))
                ? Options::RECOMMEND_NO
                : Options::RECOMMEND_YES;
            $model->is_recommend = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isRecommendIconFormat;
        }
    }

    /*
     * change "is_picking" value, false or true
     */
    public function actionChangePicking() {
        if (Yii::app()->request->isAjaxRequest) {
            $id = Yii::app()->request->getPost('id');
            $model = Post::model()->findByPk($id);
            $value = (intval($model->is_picking))
                ? Options::PICKING_NO
                : Options::PICKING_YES;
            $model->is_picking = $value;
            try {
                $model->save(false);
            } catch (Exception $ex) {
                echo $ex;
            }

            echo $model->isPickingIconFormat;
        }
    }
    
    // 批量更新
    public function actionBatchProcess() {
        if (Yii::app()->request->isPostRequest) {
            $action = strtolower(trim(Yii::app()->request->getPost('action_list')));
            switch ($action) {
                case 'update_order_pos':
                    $order_pos = Yii::app()->request->getPost('order_pos');
                    if (!empty($order_pos)) {
                        foreach ($order_pos as $key => $value) {
                            Post::model()->updateByPk($key, array('order_pos' => $value));
                        }
                    }
                    break;
                case 'delete_selected':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Post::model()->findByPk($id)->delete();
                        }
                    }
                    break;
                case 'move_to_recycle_bin':
                    $select = Yii::app()->request->getPost('select');
                    if (!empty($select)) {
                        foreach ($select as $id) {
                            $model = Post::model()->updateByPk($id, array(
                                'status' => Options::STATUS_PENDING_DELETE));
                        }
                    }
                    break;
            }

            $this->redirect(array('index', 'node' => Yii::app()->request->getPost('current_node')));
        } else {
            throw new CHttpException(400, Yii::t('common', 'invalid_request'));
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadPost($id=null) {
        if ($this->_model===null) {
            if($id!==null || isset($_GET['id']))
                $this->_model=Post::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

}
